<?php
declare (strict_types = 1);
namespace app\model\table\log;

use app\model\BaseModel;
use app\model\table\config\ConfigGlobal;
use app\model\tablenot\tool\RedisService;
use app\model\tablenot\tool\Tool;

class OperateLog extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'app_operate_log';

    private $redisKey = "insert_log_list";

    public function getRedisKey()
    {
        return $this->redisKey;
    }

    public function add($postData)
    {
        // 只有开启了 自定义日志 才添加
        if(ConfigGlobal::instance()->findValue('open_cache_log') == 1 ){
            RedisService::instance()->lpush($this->redisKey, json_encode($postData,JSON_UNESCAPED_UNICODE));
        }else{
            $obj = new self();
            $obj->save($postData);
        }
    }

    /**
     * 系统追踪日志
     * @param $name
     * @param $content
     */
    public static function traceLog($name,$content)
    {
        $HTTP_HOST = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "";
        $REQUEST_METHOD = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : "";
        $REQUEST_URI = isset($_SERVER['REQUEST_URI']) ? explode("?",$_SERVER['REQUEST_URI'])[0] : "";
        $token = isset($GLOBALS['token']) ? $GLOBALS['token'] : "";
        $url = $HTTP_HOST . $REQUEST_URI . "?token=".$token;

        $loginUserName = isset($GLOBALS['loginUserObj']) ? $GLOBALS['loginUserObj']['name'] : "";
        $dataUserName = isset($GLOBALS['dataUserObj']) ? $GLOBALS['dataUserObj']['name'] : "";
        $postData = array(
            'name' => $name,
            'url' => $url,
            'type' => $REQUEST_METHOD,
            'params' => $REQUEST_METHOD == "GET" ? json_encode($_GET, JSON_UNESCAPED_UNICODE) : json_encode($_POST, JSON_UNESCAPED_UNICODE),
            'content' => $content,
            'use_time' => '',
            'use_memory' => '',
            'plat' => isset($GLOBALS['platName']) ? $GLOBALS['platName'] : "",
            'operate_name' => $loginUserName."_".$dataUserName,
            'created_at' => date("Y-m-d H:i:s", time()),
            'login_user_id'=>$GLOBALS['loginUserObj']['id']??0,
            'data_user_id'=>$GLOBALS['dataUserObj']['id']??0,
            'ip'=>Tool::getRealIp(),
            'route'=>request()->baseUrl()
        );
        $model = new self();
        $model->add($postData);
    }
}
